/*
* 此文件主要放相关初始化方法
* */
const pfFunPrivate2 = {

  //【总入口】
  async initMain() {
    if (!this.cpIsStaticHtml) {
      //检查并初始化参数
      if (!this.param.isSet) {
        if (!this.initConfig()) {
          return null
        }
      }
      //预览的话，直接初始化数据
      if (this.param.isView || this.param.isOnlyPrintForm) {
        this.initDataForConfigList()
      }
    }

    if (!this.param.isOnlyPrintForm) {
      //初始化打印配置
      this.initPrintOnce()
    }
  },
  //检查并初始化参数
  initConfig() {
    if (!this.param) {
      this.utilMessage.error('打印失败，缺少参数【param】')
      return false
    }

    if (!this.param.configList || this.param.configList.length < 1) {
      this.utilMessage.error('打印失败，缺少参数【configList】')
      return false
    }

    this.configList = []

    let printTemplateList = this.param.that.$store.state.common.printTemplateList
    let dataviewMap = this.param.that.$store.state.common.dataviewMap
    let listEntry
    let queryWrapper
    for (let index in this.param.configList) {
      let config = this.param.configList[index]
      if (!config.printBusType) {
        this.utilMessage.error('打印失败，缺少参数【printBusType】')
        return false
      }

      if (!config.formData && !config.formDataId) {
        this.utilMessage.error('打印失败，参数【formData】【formDataId】至少有一个不为空')
        return false
      }

      let findIndex = this.constPrint.findIndex(ob => ob.busKey == config.printBusType)
      if (findIndex == -1) {
        this.utilMessage.error('打印失败，constPrint.js里面未找到')
        return false
      }

      let findOb = this.constPrint[findIndex]
      config.formViewKey = findOb.formViewKey
      config.itemViewKey = findOb.itemViewKey
      config.refKey = findOb.refKey

      //打印模板配置
      findIndex = printTemplateList.findIndex(ob => ob.busType == config.printBusType)
      if (findIndex == -1) {
        this.utilMessage.error('打印失败，打印模板配置里面没找到')
        return false
      }
      config.printTemplate = printTemplateList[findIndex]

      if (this.strings.isString(config.printTemplate.configJson)) {
        config.printTemplate.configJson = JSON.parse(config.printTemplate.configJson)
      }

      if (!config.printTemplate || config.printTemplate.fieldList.length < 1) {
        this.utilMessage.error('打印失败，未找到有效打印字段')
        return false
      }

      //主数据视图配置
      let dvMain = dataviewMap[config.formViewKey]
      if (!dvMain) {
        this.utilMessage.error('打印失败，主视图没找到')
        return false
      }
      config.formQueryUrl = dvMain.queryEntry
      config.formPrimaryKey = dvMain.primaryKey

      //子数据视图配置
      let dvItem = dataviewMap[config.itemViewKey]
      if (!dvItem) {
        this.utilMessage.error('打印失败，子视图没找到')
        return false
      }
      listEntry = dvItem.listEntry.indexOf('page') == -1 ? dvItem.listEntry : dvItem.listEntry.substring(0, dvItem.listEntry.lastIndexOf('page')) + 'list'
      config.itemQueryUrl = listEntry
      queryWrapper = this.$newWrapper()
      queryWrapper.eq(config.refKey, config.formDataId)
      config.itemQueryWrapper = queryWrapper

      this.configList.push(this.initConfigOther(config, dvMain, dvItem))
    }

    return true
  },

  //初始化表头表尾等配置
  initConfigOther(config, dvMain, dvItem) {
    console.log('dvMain', dvMain)
    console.log('dvItem', dvItem)
    console.log('printTemplate', config.printTemplate)
    config = this.initMainCOnfig(config, dvMain, dvItem)
    config = this.initItemCOnfig(config, dvMain, dvItem)
    return config
  },

  //主表配置
  initMainCOnfig(config, dvMain, dvItem) {
    return config
  },

  //明细网格配置
  initItemCOnfig(config, dvMain, dvItem) {
    let fieldList = config.printTemplate.fieldList

    //显示列
    config.columns = fieldList.filter(data => data.type == 3).sort((p1, p2) => p1.sort - p2.sort).map(data => {
      return {
        hidden: false,
        name: data.field,
        title: data.label,
        width: data.width,
        sort: data.sort,
        dict: data.dict,
        fontSize: data.fontSize,
        dateFmt: data.format,
        expression: data.expression,
        flagFontBold: data.flagFontBold,
        flagLineFeed: data.flagLineFeed,
        flagShowNegative: data.flagShowNegative,
        alignType: data.alignType,
        flagHideColon: data.flagHideColon
      }
    })

    //汇总列
    config.sumFields = fieldList.filter(data => data.summary).map(data => data.field)

    //分组列
    config.groupFields = fieldList.filter(data => data.flagGroup).map(data => data.field)

    //分单列
    config.pagebreakFields = fieldList.filter(data => data.flagBreak).map(data => data.field)

    //条码
    let barcodes = fieldList.filter(data => data.type == 1)
    if (barcodes.length > 0) {
      config.barcodes = barcodes.sort((p1, p2) => p1.sort - p2.sort).map(data => {
        return {
          name: data.field,
          text: data.label,
          col: data.width,
          type: data.format,
          flagShareRow: data.flagShareRow,
          shareRow: data.shareRow,
          alignType: data.alignType
        }
      })
    }

    //表头
    let headers = fieldList.filter(data => data.type == 2)
    if (headers.length > 0) {
      config.head = headers.sort((p1, p2) => p1.sort - p2.sort).map(data => {
        return {
          name: data.field,
          text: data.label,
          col: data.width,
          dateFmt: data.format,
          dict: data.dict,
          fontSize: data.fontSize,
          expression: data.expression,
          flagFontBold: data.flagFontBold,
          flagLineFeed: data.flagLineFeed,
          formation: data.formation,
          flagShareRow: data.flagShareRow,
          shareRow: data.shareRow,
          alignType: data.alignType
        }
      })
    }

    //表尾
    let footers = fieldList.filter(data => data.type == 4)
    if (footers.length > 0) {
      config.foot = footers.sort((p1, p2) => p1.sort - p2.sort).map((data, index) => {
        return {
          name: data.field == null ? '' + index : data.field,
          text: data.label,
          col: data.width,
          dateFmt: data.format,
          dict: data.dict,
          fontSize: data.fontSize,
          expression: data.expression,
          flagFontBold: data.flagFontBold,
          flagLineFeed: data.flagLineFeed,
          flagHideColon: data.flagHideColon,
        }
      })
    }

    return config
  },

  //初始化打印列表
  initPrintOnce() {
    global.utilPrint.isNeedCLodopfuncs(null, (that) => {
      this.initPrint()
    }, this)
  },
  //转换分单数据
  getPagebreakDataNew(responseData) {
    return this.strings.funGroupBy(responseData, (item) => {
      return this.param.pagebreakFields.map(key => item[key])
    })
  },

  //配置列表初始化数据
  async initDataForConfigList() {
    let config
    let configListNew = this.configList
    this.configList = []
    for (let configIndex in configListNew) {
      config = configListNew[configIndex]

      //主单据
      if (!configListNew[configIndex].formData) {
        await this.$ajax.get(config.formQueryUrl + '?id=' + config.formDataId).then((response) => {
          console.log('maindadta', response.data)
          if (response.code == 0) {
            configListNew[configIndex].formData = response.data
          }
        })
      }

      //子单据
      let queryWrapper = this.$newWrapper()
      queryWrapper.eq(config.refKey, config.formDataId)
      // eslint-disable-next-line no-loop-func
      await this.$ajax.get(config.itemQueryUrl + '?queryString=' + JSON.stringify(queryWrapper.queryConditions)).then((response) => {
        console.log('itemdadta', response.data)
        if (response.code == 0) {
          let tableDatas = []

          //分单
          if (this.param.pagebreakFields && this.param.pagebreakFields.length > 0) {
            tableDatas = this.getPagebreakDataNew(response.data)
          } else {
            tableDatas.push(response.data)
          }
          //分组
          // eslint-disable-next-line no-plusplus
          for (let i = 0; i < tableDatas.length; i++) {
            tableDatas[i] = this.getGroupData(tableDatas[i], config)
          }

          if (config.printTemplate.fillBlank) { //自动填充空白行
            tableDatas.forEach(data => {
              let blankCount = data.length % this.printerPageSize
              if (blankCount == 0) {
                return
              }
              blankCount = this.printerPageSize - blankCount
              while (blankCount > 0) {
                data.push({})
                blankCount -= 1
              }
            })
          }

          configListNew[configIndex].tableDatas = tableDatas
        }
      })
    }
    this.configList = configListNew
  },

  //初始化打印设置
  initPrint() {
    let param = {
      checkUsable: true
    }
    if (!this.userLodopModel || !this.userLodopModel.lodop) {
      this.userLodopModel = new window.LodopModel(param)
    }
    if (!this.userLodopModel.lodop && this.printInstall) {
      this.$confirm('未发现可用的打印服务,是否立即下载打印程序？<br><small>确认，下载安装后重新进入打印界面即可。</small><br><small>取消，将关闭打印窗口</small><br><small style="color:#e6a23c">安装时若安全软件提示修改URL关联，请允许</small>', '系统提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).then(() => {
        this.utils.downloadStatic('exe', 'CLodop_Setup_for_Win32NT')
        this.printInstall = false
        this.close()
      }).catch(() => {
        this.printInstall = false
        this.close()
      })
      return false
    }
    if (this.userLodopModel.lodop) {
      //打印机列表
      this.printers = this.userLodopModel.getPrinters() || []

      //上次所选打印机
      let printerFormName = this.utils.loadUserState(this, 'printerFormName')
      let printerOb = this.printers.find(item => item.name == printerFormName)
      printerFormName = printerOb ? printerOb.name : null
      if (!printerFormName) printerFormName = this.printers[0].name
      this.printerSelId = printerFormName

      this.printer = this.printers.find(item => item.name == printerFormName)

      //上次所选纸张
      this.printerSelPage = this.utils.loadUserState(this, 'printerFormPage')

      console.log('initPrint', this.configList[0])

      if (this.configList && this.configList.length > 0) {
        //宽度
        this.printerPageWidth = this.configList[0].printTemplate.configJson.printerPageWidth || this.printerPageWidth
        //高度
        this.printerPageHeight = this.configList[0].printTemplate.configJson.printerPageHeight || this.printerPageHeight
        //上次所选方向
        this.printerSelOrient = this.configList[0].printTemplate.configJson.printerSelOrient || '1'
        //每页数量
        this.printerPageSize = this.configList[0].printTemplate.configJson.printerPageSize || this.printerPageSize
        //每页显示标题
        this.titleEveryPage = this.configList[0].printTemplate.configJson.titleEveryPage || this.titleEveryPage
        //每页显示表头
        this.headEveryPage = this.configList[0].printTemplate.configJson.headEveryPage || this.headEveryPage
        //每页显示表尾
        this.footEveryPage = this.configList[0].printTemplate.configJson.footEveryPage || this.footEveryPage
        //自动填充空白行
        this.fillBlank = this.configList[0].printTemplate.configJson.fillBlank || this.fillBlank
      }
      //自动打印
      this.printAuto = this.utils.loadUserState(this, 'printerFormPrintAuto', null, true, this.printerFormPrintAuto)

      if (this.printAuto && !this.param.isSet) {
        this.print(false)
      }

      return true
    } else {
      return false
    }
  },
}
export default pfFunPrivate2
